// packageA/pages/userList/userList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //项目选择框
    showProject:false,
    //项目选择数据
    projectList:[],
    //项目id
    projectId:null,
    //项目名称
    projectName:'选择部门',
    //搜索关键词
    searchValue:'',
    //删除确认框
    showDelete:false,
    //删除的id
    deleteId:null,
    //删除的imei:
    deleteImei:"",
    //权限
    authority: null,
    //传参
    paramObj:{},
    //血压状态
    bloodPressureStatus:"正常",
    option2: [
      { text: '基础状态', value: 'personnelAll' },
      { text: '在岗', value: 'onDuty' },
      { text: '缺岗', value: 'offDuty' },
      { text: '请假', value: 'askLeave' },
    ],
    option3: [
      { text: '异常状态', value: 'errorStateAll' },
      { text: '摘下手环', value: 'pick' },
      { text: '离线', value: 'offline' },
      { text: '迟到', value: 'beLate' },
      { text: '早退', value: 'leaveEarly' },
    ],
    errorStateParam: "errorStateAll",
    baseStateParam: 'personnelAll',
    itemTitle: '关键词搜索',
  },

  //关键词搜索确认按钮
  keywordConfirm(){
    this.refreshListAndPage();
    this.selectComponent('#keyworkItem').toggle();
  },

  //获取关键词输入框的值
  keywordOnChange(e){
      this.setData({
        searchValue:e.detail
      })
  },

  //基础状态筛选
  baseStateChange(values){
    console.log('选中值变化：', values);
    this.setData({
      baseStateParam: values.detail
    })
    this.refreshListAndPage();
  },

  errorStateChange(values){
    console.log('选中值变化：', values);
    this.setData({
      errorStateParam: values.detail
    })
    this.refreshListAndPage();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      authority: app.globalData.authority
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);

      console.log('人员列表传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })
    }

    //获取列表数据
    this.getList();
  },
  healthDetail(e){
      console.log(e)
      console.log("详情");
      //跳转健康详情页面
      let data={
        imei:e.currentTarget.dataset.detail.imei,
        dataType:e.currentTarget.dataset.type
      }
      // wx.navigateTo({
      //   url: "/packageA/pages/healthDetail/healthDetail"
      // })
      wx.navigateTo({
        url: '/packageA/pages/healthDetail/healthDetail?paramObj=' + JSON.stringify(data)
      })
  },
  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let param = {
      page: this.data.page,
      pageSize: 10
    }

    //模糊查询
    if(this.data.searchValue){
      param.keyword = this.data.searchValue;
    }
    if(this.data.baseStateParam != ""){
      param.baseStateParam = this.data.baseStateParam
    }

    if(this.data.errorStateParam != ""){
      param.errorStateParam = this.data.errorStateParam
    }

    //员工查询
    try{
      let authority = this.data.authority;
      if(authority.manage.userCard.staff){
        let user = app.globalData.userInfo;
        param.imei = user.imei ? [user.imei] : null;
      }
    } catch (e) {
    }

    //查询某个部门（这里2022-10-22处理成按权限查询，查选择部门及下级的人员）
    if(this.data.projectId){
      param.depart = [this.data.projectId];
    }

    //按id查询人员（从项目分组来的）
    if(this.data.paramObj.imeis){
      param.imei=this.data.paramObj.imeis;
    }
    console.log(param);

    CommonService.findPersonnelAll(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        Toast.clear();
        let result=res.data.data.result;

        console.log('人员列表');
        console.log(result);

        result.forEach((item,index) => {
          //考勤值为空设为未打卡
          if(!item.currentClockState){
            item.currentClockState='未打卡';
          }
          if (item.state ==2){
            item.currentClockState = "请假"
          }

          //考勤显示相应的颜色
          switch(item.currentClockState){
            case '正常':
              item.self_class='c-1';
              break;
            case '迟到':
              item.self_class='c-2';
              break;
            case '早退':
              item.self_class='c-3';
              break;
            case '缺卡':
              item.self_class='c-4';
              break;
            case '未打卡':
              item.self_class='c-4';
              break;
            case '请假':
              item.self_class='c-4';
              break;
          }
          //判断是否在线
          if (item.ctm != null && item.ctm !=""){
              let ctm = item.ctm;
               // 兼容 iOS 的日期解析
            const cleanTimeStr = ctm.replace(/\.\d+Z$/, 'Z');
            const iosCompatibleStr = cleanTimeStr.replace('Z', ''); // 视为本地时间
        
            const targetDate = new Date(iosCompatibleStr);
            const currentDate = new Date();
            const diffMs = currentDate - targetDate;
            //self_onLine:  1:离线-并显示离线时长 0：在线  -1：从未在线
            if (diffMs>=16*60*1000){
              item.self_onLine = 1;
              //离线时长：单位（分钟）
              item.self_offLineTime = this.msToTime(diffMs)
              item.self_onLineCss = 'unOnLineCss';
            }else{
              item.self_onLine = 0;
              item.self_onLineCss = 'onLineCss';
            }
          }else{
            console.log("dfsdf");
            item.self_onLine = -1;
            item.self_onLineCss = 'unAllOnLineCss';
          }

        });

        this.setData({
          list: this.data.list.concat(result)
        })

        //只有第一个缺卡和未打卡显示提示
        let list2=this.data.list;
        for(let i=0;i<list2.length;i++){
          if(list2[i].currentClockState=='缺卡'){
            list2[i].self_word='缺卡：今日打过卡，但还有未打卡的班次';
            break;
          }
        }
        for(let i=0;i<list2.length;i++){
         if(list2[i].currentClockState=='未打卡'){
            list2[i].self_word='未打卡：今日无打卡记录';
            break;
          }
        }

        this.setData({
          list: list2
        })

      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          Toast.clear();
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      Toast.clear();
      this.setData({
        showNothing: true
      })
    })
  },

  msToTime(ms){
    if (ms <= 0) return "0天0时0分"; // 处理非正数
    
    const days = Math.floor(ms / 86400000);
    const hours = Math.floor((ms % 86400000) / 3600000);
    const minutes = Math.floor((ms % 3600000) / 60000);
    
    // 组装结果字符串（仅显示非零部分）
    const parts = [];
    if (days > 0) parts.push(`${days}天`);
    if (hours > 0) parts.push(`${hours}时`);
    if (minutes > 0) parts.push(`${minutes}分`);
    
    return parts.length > 0 ? parts.join('') : "0分钟";
  },


  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //显示项目
  onShowProject(){
    this.setData({
			showProject: true
    })
    this.getProjectList();
  },

  //查询项目
  getProjectList(){
    this.setData({
      projectList: []
    })

    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        searchAll: true,
        selectFields: ['id','name']
      }
    }

    //模糊查询
    if(this.data.valueSearchProject){
      param.data.name='%' + this.data.valueSearchProject + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];

        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });

        this.setData({
          projectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏项目
  onCloseProject(){
    this.setData({
      showProject: false,
      valueSearchProject:''
    })
  },

  //确认项目
  onConfirmProject(e){
    this.setData({
      projectId:e.detail.value.id,
      projectName:e.detail.value.text
    })
    this.onCloseProject();
    this.refreshListAndPage();
  },

  //搜索项目
  onChangeProjectVal(e){
    this.setData({
      valueSearchProject: e.detail
    })
    this.getProjectList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value,
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //跳转添加/编辑
  goToAdd(e){
    let paramObj={};

    if(e.currentTarget.dataset.detail){
      let detail=e.currentTarget.dataset.detail;
      paramObj.id=detail.id;
    }

    wx.navigateTo({
      url: "/packageA/pages/userAdd/userAdd?paramObj="+JSON.stringify(paramObj)
    })
  },

  //显示删除确认框
  onDelete(e){
    let detail=e.currentTarget.dataset.detail;
    this.setData({
      showDelete: true,
      deleteId:detail.id,
      deleteImei:detail.imei
		})
  },

  //隐藏删除确认框
  onCloseDelete(){
    this.setData({
			showDelete: false
		})
  },

  //确认删除
  confirmDelete(){
    console.log(this.data);
    let param={
      className:"user",
      data:{
        id:this.data.deleteId,
        imei:this.data.deleteImei
      }
    }

    console.log(param);
    CommonService.goDelete(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        this.confirmDeleteEs();
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //删除es中数据
  confirmDeleteEs(){
    let param={
      data:{
        id:this.data.deleteId,
        imei:this.data.deleteImei
      }
    }

    CommonService.goDeleteToEs(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('已删除');

        setTimeout(() => {
          //刷新列表和页码
          this.refreshListAndPage();
        }, 1000);

      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //跳转定位
  goToLocation({currentTarget}){
    let detail=currentTarget.dataset.detail;

    let obj={
      imei: detail.imei,
      //考勤状态，用于判断步数
      currentClockState: detail.currentClockState
    }

    wx.navigateTo({
      url: "/packageA/pages/staffLocation/staffLocation?paramObj="+JSON.stringify(obj)
    })
  },

  //跳转轨迹
  goToTrajectory({currentTarget}){
    let detail=currentTarget.dataset.detail;

    let obj={
      nickName: detail.nickName,
      lon: detail.lon,
      lat: detail.lat,
      imei: detail.imei
    }

    wx.navigateTo({
      url: "/packageA/pages/staffTrajectory/staffTrajectory?paramObj="+JSON.stringify(obj)
    })
  },

  //跳转步数统计
  goToStep({currentTarget}){
    let detail=currentTarget.dataset.detail;

    let obj={
      imei: detail.imei,
      nickName: detail.nickName,
      jobPost: detail.jobPost ? detail.jobPost : '',
      isNextDay:detail.isNextDate
    }
    console.log(obj);
    wx.navigateTo({
      url: "/packageA/pages/stepChart/stepChart?paramObj="+JSON.stringify(obj)
    })
  },

  //跳转考勤
  goToClock({currentTarget}){
    let detail=currentTarget.dataset.detail;

    let obj={
      imei: detail.imei,
      nickName: detail.nickName
    }

    wx.navigateTo({
      url: "/packageA/pages/attendancePersonDay/attendancePersonDay?paramObj="+JSON.stringify(obj)
    })
  },


  //跳转有效工作详情
  goToWorkDetail({currentTarget}){
    let detail=currentTarget.dataset.detail;
    console.log(currentTarget);
    console.log(detail);

    let obj={
      imei: detail.imei,
      nickName: detail.nickName,
      jobPost: detail.jobPost ? detail.jobPost : '',
      isNextDay:detail.isNextDate,
      dataType:currentTarget.dataset.datatype
    }
    console.log(obj);
    wx.navigateTo({
      url: "/packageB/pages/effectiveWorkAndStepDetail/effectiveWorkAndStepDetail?paramObj="+JSON.stringify(obj)
    })
  },


  //跳转进出围栏记录
  goToFenceRecord({currentTarget}){
    let detail=currentTarget.dataset.detail;
    console.log(detail);
    let data = {
      imei:detail.imei,
      nickName:detail.nickName
    }
    wx.navigateTo({
      url: "/packageA/pages/outInFenceCount/outInFenceCount?paramObj="+JSON.stringify(data)
    })
  },

  //显示提示
  showTips({currentTarget}){
    let detail=currentTarget.dataset.detail;
    console.log(detail);
    //查询请假记录最后新一条数据
    let params = {
      className: 'personLeaveRecord',
      data: {
          "applicant.id":detail.id,
          selectFields: ["id", "project", "applicant", "leaveType", "leaveStartTime", "leaveEndTime", "company", "operator", "createTime","expired","stopTime","leaveReason"],
          //nbl: Base64.encode(util.timeFormatDay(new Date())),
          sort: {
              createTime: -1
          },
          page: {
            page: 1,
            pageSize: 1,
        }
      }
  }
  console.log(params);
  CommonService.goFindList(params).then(res => {
    if (res.data.data && res.data.data.result && res.data.data.result.length) {
        let result = res.data.data.result;
        console.log('子菜单列表');
        console.log(result);
        if (result!=null && result.length>0){
          Toast({
            message: result[0].leaveReason,
            duration: 3000
          });
        }else{
          Toast({
            message: "",
            duration: 2000
          });
        }
         
    }
  }).catch((error) => {
      console.error(error);
  }).finally(() => {
     
  });
    // Toast({
    //   message: detail,
    //   duration: 2000
    // });
  },

  //脱岗提示
  showOffTip(){
    Toast({
      message: '人员脱岗',
      duration: 2000
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

    if(this.data.notMore && this.data.baseStateParam != "offDuty"){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})
